import React, { useState } from 'react'
import { nanoid } from 'nanoid'

import { connect } from 'react-redux'

import { addPersonAction } from '../redux/actions/person';

function Person(props) {
    const {
        persons,
        addPersonAction,
        count
    } = props

    // 存储一个人的信息
    const [personInfo, setPersonInfo] = useState({
        id: nanoid(),
        name: "",
        age: "",
    })

    // 添加一个人
    const addPerson = () => {
        console.log(personInfo, "addPerson");
        addPersonAction(personInfo)
        setPersonInfo({
            id: nanoid(),
            name: "",
            age: "",
        })
        console.log(personInfo)
    }
    return (
        <>
            <h1>我是Person组件,上方求和为{count}</h1>
            <input
                value={personInfo.name}
                onChange={(e) =>
                    setPersonInfo({ ...personInfo, name: e.target.value })
                }
                type="text"
            /> &nbsp;
            <input
                value={personInfo.age}
                onChange={(e) =>
                    setPersonInfo({ ...personInfo, age: e.target.value })
                }
                type="text"
            /> &nbsp;
            <button onClick={() => {
                addPerson()
            }}>添加</button>
            <ul>
                {persons && persons.length > 0 ?
                    persons.map((person) => (
                        <li key={person.id}>姓名:{person.name} - 年龄:{person.age}</li>
                    )) : <li>暂无数据</li>}
            </ul>
        </>
    )
}

export default connect(
    state => ({
        persons: state.personReducer.persons,
        count: state.countReducer.count
    }),
    {
        addPersonAction
    }
)(Person)
